#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "list.h"

/* create a circular linked list */
struct list * create_circular_link()
{
  struct list * new;

  new = (struct list *) malloc (sizeof(struct list));
  if (!new) {
    printf("cannot create a list");
    return NULL;
  }
  printf(" news %p \n", new);

  new->num = 0;
  new->next = new;	// circular
  printf("new->next = new %p:%p\n", new->next, new);

  return new;
}

/* insert a new node */
struct list * insert(struct list * node, int data)
{
  struct list * head, * new, * src, * des;
  int i = 0;

  head = node; 
  src = node;
  des = head->next; 

  while(des != head) {	// 找到最后一个节点
    src = des;			// 指向后一个节点
    des = des->next; 
    printf("while src des %p:%p \n", src, des);
  }

  new = (struct list *)malloc(sizeof(struct list));
  if(!new){
    printf("TailInsert:cannot create a list");
    return NULL;
  }
  new->num = data; 
  new->next = src->next; // 新节点next指向头节点,形成循环
  src->next = new;		 // 接上新节点
  printf("src->next = new %p:%p, new->next = %p\n", src->next, new, new->next);

  return head;
}

void display(struct list * node)
{
  struct list * src, * des;

  src = node;
  des = node->next;

  while(des != src){
    printf(" %d ->",des->num);
    des=des->next;
  }
  printf("\n\n");
}

main()
{ 
  int i;
  struct list * node, * cur;

  node = create_circular_link();
  printf("node:%p\n", node);

  for(i = 1; i < 11; i++)
    node = insert(node,i);

  printf("node:%p\n", node);

  display(node); 
}
